package org.usmile.algorithms.learn.sort;

import java.util.Random;

/**
 * 快速排序
 */
public class QuickSorter {
    public void sort(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int left = 0;
        int right = nums.length - 1;

        sort(nums, left, right);
    }

    private void sort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }

        int partition = partition(nums, left, right);
        sort(nums, left, partition - 1);
        sort(nums, partition + 1, right);
    }

    private int partition(int[] nums, int left, int right) {
        int randomIndex = new Random().nextInt(right - left + 1) + left;
        int pivot = nums[randomIndex];
        swap(nums, randomIndex, right);

        int i = left;
        int less = left;
        while (i < right) {
            if (nums[i] < pivot) {
                if (i != less) {
                    swap(nums, i, less);
                }
                less++;
            }
            i++;
        }

        swap(nums, less, right);

        return less;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 20; i++) {
            System.out.println(new Random().nextInt(5 + 1) + 4);
        }
//        int[] nums = new int[]{1, 4, 3, 2, 10, 20, 18, 9, 7, 5, 13};
//        new QuickSorter().sort(nums);
//
//        System.out.println(Arrays.toString(nums));
    }
}